from odoo import models, fields, api
from odoo import exceptions # will be used in the code
class MeasWorkSubWizard(models.TransientModel):
    _name='meas.work.sub.wizard'
    _description="采集多数据表头"
    work_sub_id=fields.Many2one('meas.work.sub',string="工单明细")
    decimal=fields.Boolean('3位精度')
    min_value=fields.Float('允许最小值',related="work_sub_id.min_value",digits="Meas of Unit")
    min_value2=fields.Float('允许最小值',related="work_sub_id.min_value2",digits="two of Unit")
    max_value=fields.Float('允许最大值',related="work_sub_id.max_value",digits="Meas of Unit")
    max_value2=fields.Float('允许最大值',related="work_sub_id.max_value2",digits="two of Unit")
    avg_val=fields.Float('平均值',digits='Meas of Unit',compute="_compute_avg_val")
    compute_wizard_ids=fields.One2many('meas.compute.wizard','work_sub_wizard_id')
    
    @api.model
    def default_get(self, default_fields):
        result = super(MeasWorkSubWizard,self).default_get(default_fields)
        active_id = self.env.context.get('active_id')
        meas_work_sub=self.env['meas.work.sub'].browse(active_id)
        real_value=meas_work_sub.real_value
        real_value2=meas_work_sub.real_value2
        decimal=meas_work_sub.decimal

        result['work_sub_id']=active_id
        result['decimal']=decimal
        result['avg_val']=real_value if decimal else real_value2
        return result    

    @api.depends('compute_wizard_ids')
    def _compute_avg_val(self):
        for r in self:
            i=0
            value=0.000
            for rec in r.compute_wizard_ids:
                if rec.value != 0:
                    i=i+1
                    value= value + rec.value
            if i !=0:        
                # r.compute=value/i
                r.avg_val=value/i
            else:
                # r.compute=0
                r.avg_val=0

    def finish_action(self):
        work_sub_id=self.work_sub_id.id
        decimal=self.decimal
        if decimal:
            self.env['meas.work.sub'].browse(work_sub_id).real_value=self.avg_val
        else:
            self.env['meas.work.sub'].browse(work_sub_id).real_value2=self.avg_val


class MeasComputeWizard(models.TransientModel):
    _name="meas.compute.wizard"
    _description="采集多数据"
    # _rec_name="value"

    value=fields.Float('采集值',digits="Meas of Unit",default=False)
    work_sub_wizard_id=fields.Many2one('meas.work.sub.wizard')

